package com.javasm.controller;

import com.alibaba.fastjson.JSON;
import com.javasm.entity.ReturnCodeEnum;
import com.javasm.entity.ReturnResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.UUID;

/**
 * @version 0.1
 * @className: UploadServlet
 * @description:
 * @author: gfs
 * @date: 2025/6/27 14:57
 * @since: jdk17
 */
@WebServlet("/myupload")
@MultipartConfig
public class UploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //tomcat会按webkit格式自动解析流中的文件数据
        Part myFile = req.getPart("myFile");

        //指定位置存文件
        //tomcat开放的目录
        String basePath = req.getServletContext().getRealPath("/");
        System.out.println(basePath);
        /*
        *
        * 1 原文件名不重要
        *   根据生成ID的逻辑 生成唯一标记替换文件名

        * 2 原文件名重要
        *   通过不同的目录 存不同人传的文件
        *   登录用户信息 用户名 合作公司名 日期
        *
        * */


        String folderPath = "upload/";
        //原文件名
        //生成随机编号
        String fileName = myFile.getSubmittedFileName();
        UUID uuid = UUID.randomUUID();
        //保留扩展名 组合唯一标记生成新文件名
        String newFileName = uuid+ fileName.substring(fileName.lastIndexOf("."));
        //String path = "E://test.png";


        //把文件写入本地文件
        myFile.write(basePath+folderPath+newFileName);


        ReturnResult returnResult = new ReturnResult();

        returnResult.setCode(ReturnCodeEnum.UPLOAD_SUCCESS.getCode());
        returnResult.setMsg(ReturnCodeEnum.UPLOAD_SUCCESS.getMsg());
        returnResult.setReturnData("http://localhost:8080/projectDemo/"+folderPath+newFileName);
        //用输出流输出JSON字符串
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.print(JSON.toJSONString(returnResult));
        writer.close();




    }
}
